﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;


namespace download
{
    public class DownloadHandler : IHttpHandler
    {
        
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse Response = context.Response;
            HttpRequest Request = context.Request;
            System.IO.Stream iStream = null;
            byte[] buffer = new Byte[10240];
            int length;
            long dataToRead;
            try
            {
               //string id = context.Request["id"];
               //string filename = context.Request["filename"];
                //string aa = context.Session["test1"] as string;
                string filepath = context.Request["filepath"];
                string filename = context.Request["filename"];

                //string filepath = System.Web.HttpContext.Current.Session["selFilePath"] as string;
                //string filename = System.Web.HttpContext.Current.Session["test1"] as string;

                if (string.IsNullOrEmpty(filename))
                {
                   Response.Write("<script type='text/javascript'>alert('没有附件！');</script>");
                    return;
                }

                if (!File.Exists(filepath))
                {
                    Response.Write("<script type='text/javascript'>alert('你查看的文档不存在！');</script>");
                     return;
                }
                

                //如果客户端使用 Microsoft Internet Explorer，则需要一次url编码，用于解决文件名乱码问题
                if (context.Request.UserAgent.Contains("MSIE") || context.Request.UserAgent.Contains("msie"))
                {
                    context.Server.UrlEncode(filename);
                }

                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                System.IO.FileAccess.Read, System.IO.FileShare.Read);
                Response.Clear();
                dataToRead = iStream.Length;
                long p = 0;
                if (Request.Headers["Range"] != null)
                {
                    Response.StatusCode = 206;
                    p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                }
                if (p != 0)
                {
                    Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
                }
                Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filepath))));
                iStream.Position = p;
                dataToRead = dataToRead - p;
                while (dataToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10240);
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        buffer = new Byte[10240];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
                Response.End();
            }
        }
        public bool IsReusable
        {
            get { return true; }
        }
    }

}
